package com.qf.dao.impl;

import com.alibaba.fastjson.parser.deserializer.AbstractDateDeserializer;
import com.qf.dao.AddressDao;
import com.qf.pojo.Address;
import com.qf.utils.DBTools;
import com.qf.utils.SQL;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AddressDaoImpl implements AddressDao {
    QueryRunner qr=new QueryRunner(DBTools.getDataSource());
    BeanListHandler<Address> bean=new BeanListHandler<Address>(Address.class);

    @Override
    public int addOne(Address address) {

        String sql="insert into address VALUES(null,?,?,?,?,?)";
        try {
            return qr.update(sql,address.getUid(),address.getContent(),address.getUname(),address.getUtel(),address.getDefaults());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Address> selectAll(Integer uid) {

        String sql="SELECT"+ SQL.ADDRESS +"FROM ADDRESS WHERE u_id=?";
        try {
            return qr.query(sql,bean,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int clearDefault(Integer uid) {
        String sql="UPDATE ADDRESS SET DEFAULTS=0 WHERE u_id=?";
        try {
            return qr.update(sql,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int setDefault(Integer uid, Integer aid) {
        String sql="UPDATE ADDRESS SET DEFAULTS=1 WHERE u_id=? and addr_id=?";
        try {
            return qr.update(sql,uid,aid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Address selectOne(Integer aid) {
        BeanHandler<Address> beanHandler= new BeanHandler<Address>(Address.class);
        String sql="SELECT"+ SQL.ADDRESS +"FROM ADDRESS WHERE addr_id=?";
        try {
            return qr.query(sql,beanHandler,aid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}





